/*

File: XMLReader.m
Abstract: Uses NSXMLParser to extract the contents of an XML file and map it
Objective-C model objects.

Version: 1.7

Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms.  If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple.  Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.

The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (C) 2008 Apple Inc. All Rights Reserved.

*/

#import "cliqsetAppDelegate.h"
#import "XMLReader.h"

@implementation XMLReader

@synthesize currentContactObject     = _currentContactObject;
@synthesize currentPhoneObject       = _currentPhoneObject;
@synthesize currentTagObject         = _currentTagObject;
@synthesize currentAddressObject     = _currentAddressObject;
@synthesize currentEmailObject       = _currentEmailObject;
@synthesize currentURLObject         = _currentURLObject;
@synthesize currentIMObject          = _currentIMObject;
@synthesize contentOfCurrentProperty = _contentOfCurrentProperty;

@synthesize currentPrimary;
@synthesize currentType;
@synthesize currentPhoneNumber;
@synthesize currentURL;
@synthesize currentTag;
@synthesize currentAddress;
@synthesize currentStreetAddress;
@synthesize currentLocality;
@synthesize currentRegion;
@synthesize currentCountry;
@synthesize currentPostalCode;
@synthesize currentNetwork;
@synthesize currentScreenName;

NSString *strIM            = @"IM";
NSString *strName          = @"Name";
NSString *strNetwork       = @"Network";
NSString *strStreetAddress = @"StreetAddress";
NSString *strLocality      = @"Locality";
NSString *strRegion        = @"Region";
NSString *strCountry       = @"Country";
NSString *strPostalCode    = @"PostCode";
NSString *strEmailAddress  = @"EmailAddress";
NSString *strAddress       = @"Address";
NSString *strContact       = @"Contact";
NSString *strContactID     = @"ContactIdentifier";
NSString *strGivenName     = @"GivenName";
NSString *strMiddleName    = @"MiddleName";
NSString *strFamilyName    = @"FamilyName";
NSString *strNotes         = @"Notes";
NSString *strCompany       = @"Company";
NSString *strPosition      = @"Position";
NSString *strPhotoURL	   = @"PhotoURL";
NSString *strTags          = @"Tags";
NSString *strTag           = @"Tag";
NSString *strType          = @"Type";
NSString *strPrimary       = @"Primary";

NSString *strPhoneNumber   = @"PhoneNumber";
NSString *strPhones        = @"Phones";
NSString *strPhone         = @"Phone";
NSString *strURL           = @"URL";
NSString *strURLs          = @"URLS";

NSString *strEmpty         = @"";
NSString *strOne           = @"1";
NSString *strZero          = @"0";
NSString *strCr            = @"\r";
NSString *strNl            = @"\n";

-(XMLReader*)init {
	[super init];

	_currentPhoneObject   = nil;
	_currentTagObject     = nil;
	_currentURLObject     = nil;
	_currentAddressObject = nil;
	_currentEmailObject   = nil;
	_currentIMObject      = nil;
	
	return self;
}

-(void)resetVars {
	
	self.contentOfCurrentProperty = nil;
	
	if (@selector(_currentContactObject) && _currentContactObject!=nil && self.currentContactObject) {
		[self.currentContactObject release];
		self.currentContactObject = nil;
	}	
	if (@selector(_currentPhoneObject) && _currentPhoneObject!=nil && self.currentPhoneObject) {
		[self.currentPhoneObject release];
		self.currentPhoneObject = nil;
	}	
	if (@selector(_currentURLObject) && _currentURLObject!=nil && self.currentURLObject) {
		[self.currentURLObject release];
		self.currentURLObject = nil;
	}	
	if (@selector(_currentTagObject) && _currentTagObject!=nil && self.currentTagObject) {
		[self.currentTagObject release];
		self.currentTagObject = nil;
	}	
	if (@selector(_currentEmailObject) && _currentEmailObject!=nil && self.currentEmailObject) {
		[self.currentEmailObject release];
		self.currentEmailObject = nil;
	}	
	if (@selector(_currentAddressObject) && _currentAddressObject!=nil && self.currentAddressObject) {
		[self.currentAddressObject release];
		self.currentAddressObject = nil;
	}	
	if (@selector(_currentIMObject) && _currentIMObject!=nil && self.currentIMObject) {
		[self.currentIMObject release];
		self.currentIMObject = nil;
	}	
}

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
	[self resetVars];
}

- (void)parseXMLFileAtData:(NSData *)data parseError:(NSError **)error
{	
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];

    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
	
	[self resetVars];
    
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) {
        elementName = qName;
    }
        
	if ([elementName isEqualToString:strContact]) {
		
		[self resetVars];
		
        // An entry in the RSS feed represents an article, so create an instance of it.
        self.currentContactObject = [[Contact alloc] init];
	} else if ([elementName isEqualToString:strIM]) {
		if (self.currentIMObject) {[self.currentIMObject release];}
        self.currentIMObject          = [[IM alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strStreetAddress]) {
		if (self.currentAddressObject) {[self.currentAddressObject release];}
        self.currentAddressObject     = [[Address alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strNetwork]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strContactID]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strGivenName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strMiddleName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strFamilyName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strNotes]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strCompany]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strPosition]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strPhotoURL]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strType]) {
		self.currentType              = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strPrimary]) {
		self.currentPrimary           = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strPhoneNumber]) {
		self.currentPhoneNumber       = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strStreetAddress]) {
		self.currentStreetAddress     = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strLocality]) {
		self.currentLocality          = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strRegion]) {
		self.currentRegion            = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strCountry]) {
		self.currentCountry           = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strPostalCode]) {
		self.currentPostalCode        = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strAddress]) {
		self.currentAddress           = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strURL]) {
		if (self.currentURLObject) {[self.currentURLObject release];}
        self.currentURLObject         = [[URL alloc] init];
		self.currentURL               = [NSMutableString string];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strTag]) {
		if (self.currentTagObject) {[self.currentTagObject release];}
        self.currentTagObject         = [[Tag alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
		self.currentTag               = [NSMutableString string];
	} else if ([elementName isEqualToString:strPhone]) {
		if (self.currentPhoneObject) {[self.currentPhoneObject release];}
        self.currentPhoneObject       = [[Phone alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strEmailAddress]) {
		if (self.currentEmailObject) {[self.currentEmailObject release];}
        self.currentEmailObject       = [[EmailAddress alloc] init];
        self.contentOfCurrentProperty = [NSMutableString string];
    } else {
        // The element isn't one that we care about, so set the property that holds the 
        // character content of the current element to nil. That way, in the parser:foundCharacters:
        // callback, the string that the parser reports will be ignored.
        self.contentOfCurrentProperty = nil;
		}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
    if (qName) {
        elementName = qName;
    }

	// Tag
    if ([elementName isEqualToString:strTag]) {
		if (self.contentOfCurrentProperty && self.currentTagObject && self.currentContactObject) {
			self.currentTagObject.tag = self.contentOfCurrentProperty;
			[self.currentContactObject.tags addObject:self.currentTagObject];
		}
	}
	
	// Name
    if ([elementName isEqualToString:strName]) {
		if (self.contentOfCurrentProperty) {
			self.currentScreenName = self.contentOfCurrentProperty;
		} else {
			self.currentScreenName = (NSMutableString*)strEmpty;
		}
	}
	
	// Network
    if ([elementName isEqualToString:strNetwork]) {
		if (self.contentOfCurrentProperty) {
			self.currentNetwork = self.contentOfCurrentProperty;
		} else {
			self.currentNetwork = (NSMutableString*)strEmpty;
		}
	}
	
	// URL
    if ([elementName isEqualToString:strURL]) {
		if (self.currentURLObject && self.currentContactObject) {
			if (![self.contentOfCurrentProperty isEqualToString:@"false"]) {
				self.currentURLObject.type        = self.currentType;
				self.currentURLObject.primary     = [self.currentPrimary boolValue];
				self.currentURLObject.url         = self.contentOfCurrentProperty;
				[self.currentContactObject.urls addObject:self.currentURLObject];
			}
		}
	}
	
	// IM
    if ([elementName isEqualToString:strIM]) {
		if (self.currentIMObject && self.currentContactObject) {
			self.currentIMObject.network     = self.currentNetwork;
			self.currentIMObject.primary     = [self.currentPrimary boolValue];
			self.currentIMObject.name        = self.currentScreenName;
			[self.currentContactObject.imScreenNames addObject:self.currentIMObject];
		}
	}
	
	// Email Address
    if ([elementName isEqualToString:strEmailAddress]) {
		if (self.currentEmailObject && self.currentContactObject) {
			self.currentEmailObject.type        = self.currentType;
			self.currentEmailObject.primary     = [self.currentPrimary boolValue];
			self.currentEmailObject.address     = self.currentAddress;
			[self.currentContactObject.emailAddresses addObject:self.currentEmailObject];
		}
	}

	// Phone
    if ([elementName isEqualToString:strPhone]) {
		if ( self.currentPhoneObject && self.currentContactObject) {
			self.currentPhoneObject.type        = self.currentType;
			self.currentPhoneObject.primary     = [self.currentPrimary boolValue];
			self.currentPhoneObject.phoneNumber = self.currentPhoneNumber;
			[self.currentContactObject.phones addObject:self.currentPhoneObject];
		}
	}
	
	// Street Address
    if ([elementName isEqualToString:strStreetAddress]) {
		if (self.contentOfCurrentProperty) {
			self.currentStreetAddress = self.contentOfCurrentProperty;
		} else {
			self.currentStreetAddress = (NSMutableString*)strEmpty;
		}
	}
	
	// Locality
    if ([elementName isEqualToString:strLocality]) {
		if (self.contentOfCurrentProperty) {
			self.currentLocality = self.contentOfCurrentProperty;
		} else {
			self.currentLocality = (NSMutableString*)strEmpty;
		}
	}
	
	// Region
    if ([elementName isEqualToString:strRegion]) {
		if (self.contentOfCurrentProperty) {
			self.currentRegion = self.contentOfCurrentProperty;
		} else {
			self.currentRegion = (NSMutableString*)strEmpty;
		}
	}
	
	// Country
    if ([elementName isEqualToString:strCountry]) {
		if (self.contentOfCurrentProperty) {
			self.currentCountry = self.contentOfCurrentProperty;
		} else {
			self.currentCountry = (NSMutableString*)strEmpty;
		}
	}
	
	// Postal Code
    if ([elementName isEqualToString:strPostalCode]) {
		if (self.contentOfCurrentProperty) {
			self.currentPostalCode = self.contentOfCurrentProperty;
		} else {
			self.currentPostalCode = (NSMutableString*)strEmpty;
		}
		if (self.currentAddressObject && self.currentContactObject) {
			self.currentAddressObject.type          = self.currentType;
			self.currentAddressObject.primary       = [self.currentPrimary boolValue];
			self.currentAddressObject.streetAddress = self.currentStreetAddress;
			self.currentAddressObject.locality      = self.currentLocality;
			self.currentAddressObject.region        = self.currentRegion;
			self.currentAddressObject.country       = self.currentCountry;
			self.currentAddressObject.postalCode    = self.currentPostalCode;
			[self.currentContactObject.addresses addObject:self.currentAddressObject];
		}
	}
	
	// Address
    if ([elementName isEqualToString:strAddress]) {
		if (self.contentOfCurrentProperty) {
			self.currentAddress = self.contentOfCurrentProperty;
		} else {
			self.currentAddress = (NSMutableString*)strEmpty;
		}
	}
	
	// Type
    if ([elementName isEqualToString:strType]) {
		if (self.contentOfCurrentProperty) {
			self.currentType = self.contentOfCurrentProperty;
		} else {
			self.currentType = (NSMutableString*)strEmpty;
		}
	}
	
	// Primary
    if ([elementName isEqualToString:strPrimary]) {
		if (self.contentOfCurrentProperty) {
			self.currentPrimary = self.contentOfCurrentProperty;
		} else {
			self.currentPrimary = (NSMutableString*)strEmpty;
		}
	}
	
	// Phone Number
    if ([elementName isEqualToString:strPhoneNumber]) {
		if (self.contentOfCurrentProperty) {
			self.currentPhoneNumber = self.contentOfCurrentProperty;
		} else {
			self.currentPhoneNumber = (NSMutableString*)strEmpty;
		}
	}
    
	// Photo URL
    if ([elementName isEqualToString:strPhotoURL]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.photoURL = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.photoURL = (NSMutableString*)strEmpty;
		}
	}
	
	// Contact ID
    if ([elementName isEqualToString:strContactID]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.contactIdentifier = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.contactIdentifier = (NSMutableString*)strEmpty;
		}
	}
    
	// Given Name
    if ([elementName isEqualToString:strGivenName]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.givenName = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.givenName = (NSMutableString*)strEmpty;
		}
	}
    
	// Middle Name
    if ([elementName isEqualToString:strMiddleName]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.middleName = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.middleName = (NSMutableString*)strEmpty;
		}
	}
    
	// Family Name
    if ([elementName isEqualToString:strFamilyName]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.familyName = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.familyName = (NSMutableString*)strEmpty;
		}
	}

	// Notes
    if ([elementName isEqualToString:strNotes]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.notes = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.notes = (NSMutableString*)strEmpty;
		}
	}
	
	// Company
    if ([elementName isEqualToString:strCompany]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.company = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.company = (NSMutableString*)strEmpty;
		}
	}
	
	// Position
    if ([elementName isEqualToString:strPosition]) {
		if (self.contentOfCurrentProperty) {
			self.currentContactObject.position = self.contentOfCurrentProperty;
		} else {
			self.currentContactObject.position = (NSMutableString*)strEmpty;
		}
	}
	
	if ([elementName isEqualToString:strContact]) {
		// we will write the Contact to an array here...
		//if (self.currentArticleObject && ![self.currentArticleObject.title isEqualToString:strEmpty] && self.currentArticleObject.title) {
		if (self.currentContactObject) {
			[(id)[[UIApplication sharedApplication] delegate] performSelectorOnMainThread:@selector(addContact:) withObject:self.currentContactObject waitUntilDone:YES];
			}
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentOfCurrentProperty) {
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
		if (string) {
			string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
			string = [string stringByReplacingOccurrencesOfString:strCr withString:strEmpty];
			string = [string stringByReplacingOccurrencesOfString:strNl withString:strEmpty];
			[self.contentOfCurrentProperty appendString:string];
			}
    }
}

-(void) dealloc {
	
	[currentScreenName release];
	[currentNetwork release];
	[currentPostalCode release];
	[currentCountry release];
	[currentRegion release];
	[currentLocality release];
	[currentStreetAddress release];
	[currentAddress release];
	[currentURL release];
	[currentType release];
	[currentTag release];
	[currentPrimary release];
	[currentPhoneNumber release];
	[_contentOfCurrentProperty release];
	[_currentContactObject release];
	[_currentPhoneObject release];
	[_currentTagObject release];
	[_currentURLObject release];
	[_currentEmailObject release];
	[_currentAddressObject release];
	[_currentIMObject release];
	
	[super dealloc];
}

@end
